import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report,roc_auc_score


def analysis():
    names = ["Sample code number", "Clump Thickness", "Uniformity of Cell Size", "Uniformity of Cell Shape",
             "Marginal Adhesion", "Single Epithelial Cell Size", "Bare Nuclei", "Bland Chromatin", "Normal Nucleoli",
             "Mitoses", "Class"]
    # 1.获取数据
    # 下载地址 https://archive.ics.uci.edu/dataset/15/breast+cancer+wisconsin+original
    data = pd.read_csv("E:\\pythonProject\\ai-study\\逻辑回归学习\\example\\breast-cancer-wisconsin.data", names=names)

    # 2. 基本数据处理，处理缺失值，数据中缺失值用 ? 标识，需要替换成nan，然后删除
    data = data.replace(to_replace="?", value=np.nan)
    data = data.dropna()
    # 确定特征值
    x = data.iloc[:, 1:-1]  # 特征字段为前面2~10行,即除去第一行样本编号和最后一个目标值
    # 目标值
    y = data.iloc[:, -1]  # 或者用 y = data["Class"]

    # 分割数据
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22, test_size=0.2)

    # 3.特征工程（标准化）
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.机器学习（逻辑回归）
    estimator = LogisticRegression()
    estimator.fit(x_train, y_train)

    result = estimator.score(x_test, y_test)
    print("准确率=", result)

    y_pre = estimator.predict(x_test)
    print("预测值=", y_pre)

    # 分类评估报告
    report = classification_report(y_test,y_pre,labels=[2,4],target_names=["良性","恶性"])
    print(report)

    # 把样本值转为布尔类型
    y_test = np.where(y_test > 3, 1, 0)  # 当4（恶性）的时候为true，反之
    score=roc_auc_score(y_test,y_pre) # 目标值和预测值比较
    print(score)
    return None

if __name__ == '__main__':
    analysis()
